package Clases;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Youtube.java
 *
 * Created on 09-mar-2010, 13:51:34
 */


import com.google.gdata.client.youtube.*;
import com.google.gdata.data.youtube.*;
import com.google.gdata.util.*;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.mediarss.MediaKeywords;
import com.google.gdata.data.media.mediarss.MediaPlayer;


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Vector;

/**
 *
 * @author eneko
 */
public class Youtube extends javax.swing.JFrame {

    private String palabraClave;
    private YouTubeService service=null;
    public static String FEED_VIDEOS="http://gdata.youtube.com/feeds/api/videos";
    private static final  BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(System.in)); 
    
    /** Creates new form Youtube */
    /*public Youtube()
    {
        initComponents();
    }*/
    
    public Youtube(String clave) {
        palabraClave=clave;
    }


    private static String readLine() throws IOException {
        return bufferedReader.readLine();
    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */

    /*
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        /*jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.setText("Introduzca aquí las palabras clave de búsqueda que estime oportunas");

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(139, 139, 139)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(291, 291, 291)
                        .addComponent(jButton1)))
                .addContainerGap(140, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(132, 132, 132)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(42, 42, 42)
                .addComponent(jButton1)
                .addContainerGap(196, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
         *

         */

    /*private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        //YouTubeQuery query = null;
        //VideoFeed videoFeed=new VideoFeed();
        YouTubeMediaGroup mediaGroup=null;
        MediaPlayer mediaPlayer=null;
        MediaKeywords mediaKeywords=null;
        String keywords;

        searchFeed(service);

    }//GEN-LAST:event_jButton1ActionPerformed

  
   */

   /**
   * Busca en el FEED_VIDEOS por términos y imprime el resultado.
   *
   * @param service un objeto YoutubeService
   */
  private static Vector searchFeed(YouTubeService service)
  {
    Vector sal=new Vector();
    int indice=0;
    try{
        YouTubeQuery query = new YouTubeQuery(new URL(FEED_VIDEOS));
        // order results by the number of views (most viewed first)
        query.setOrderBy(YouTubeQuery.OrderBy.VIEW_COUNT);

        // do not exclude restricted content from the search results
        // (by default, it is excluded)
        query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
        //System.out.println("\nEnter search terms: ");
        //String searchTerms = readLine();

        query.setFullTextQuery("Avalanch");

        VideoFeed videoFeed = service.query(query, VideoFeed.class);

        for (VideoEntry ve : videoFeed.getEntries()) {
          indice++;
          //printVideoEntry("\n\n Vídeo número "+indice+"\n", ve,"videos_youtube.txt");
          sal.add(getVideosId(ve));//Para cada entrada de vídeo, cogemos su ID.
        }
        System.out.println();
    }
    catch(IOException ex){
        ex.printStackTrace();
    }
    catch(ServiceException ex){
        ex.printStackTrace();
    }
    return sal;
  }


    /**
   * Imprime un videoEntry
   *
   * @param prefix                   Prefijo a mostrar antes de cada entrada
   * @param videoEntry               VideoEntry a imprimir.
   * @param filename                 Nombre del fichero en el que escribiremos.
   */
    private static void printVideoEntry(String prefix, VideoEntry videoEntry,String filename){
      //HiloFile hf;
      ProcessFile pf=new ProcessFile(filename);
      String tags;
      try{
        //System.out.println(prefix);
        //hf=new HiloFile(prefix,filename);
        pf.write(prefix);

        if (videoEntry.getTitle() != null) {
          //System.out.printf("Title: %s\n", videoEntry.getTitle().getPlainText());
          //hf=new HiloFile(+"\n",filename);
          pf.write("Title:"+ videoEntry.getTitle().getPlainText()+"\n");
        }
        if (videoEntry.getSummary() != null) {
          //System.out.printf("Summary: %s\n",
              //videoEntry.getSummary().getPlainText());
          pf.write("Summary: "+videoEntry.getSummary().getPlainText()+"\n");
        }
        YouTubeMediaGroup mediaGroup = videoEntry.getMediaGroup();
        System.out.println("ID = "+mediaGroup.getVideoId());
        if(mediaGroup != null) {
          MediaPlayer mediaPlayer = mediaGroup.getPlayer();
          //System.out.println("Web Player URL: " + mediaPlayer.getUrl());
          pf.write("Web Player URL: " + mediaPlayer.getUrl()+"\n");
          MediaKeywords keywords = mediaGroup.getKeywords();
          //System.out.print("Keywords: ");
          //hf=new HiloFile(,filename);
          tags="Tags = ";
          pf.write(tags);
          for(String keyword : keywords.getKeywords()) {
            //System.out.print(keyword + ",");
            pf.write(keyword + ",");
          }
          //System.out.println();
        }
     }
     catch(Exception ex){
         ex.printStackTrace();
     }
    }

   /**
   * Guarda en un vector el id de la entrada de vídeo X.
   *
   * @param entry   Entrada de vídeo a procesar.
   */
    private static Vector getVideosId(VideoEntry entry)
    {
        Vector salida=new Vector();
        
        YouTubeMediaGroup mediaGroup = entry.getMediaGroup();

        salida.add(mediaGroup.getVideoId());

        return salida;
    }

   /**
   * Genera el embed de todos los vídeos que queramos mostrar.
   *
   * @param Vector   Vector con los ID de los vídeos.
   */
    private static void genEmbed(Vector v)
    {
        ProcessFile pf=new ProcessFile("Embeds.txt");
        for(int i=0;i<v.size();i++)
        {
            String linkYouTubePrefix="http://www.youtube.com/v/";
            String linkYouTubeSuffix="&hl=es_Es&js=1";
            String part1="<object width='480' height='385'><param name='movie' value='";
            part1=part1.concat(linkYouTubePrefix+v.get(i).toString()+linkYouTubeSuffix);
            String part2="'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='";
            part1=part1.concat(part2.concat(linkYouTubePrefix+v.get(i).toString()+linkYouTubeSuffix));
            String part3="' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='480' height='385'></embed></object>";
            part1=part1.concat(part3);
            part1=part1.replace("'", "\"");
            part1=part1.replace("[","");
            part1=part1.replace("]","");
            pf.write(part1+"\n");
        }
    }

    public Vector readEmbeds(String filename)
    {
        String linea,video=null;
        FileReader fr=null;
        BufferedReader bfr=null;
        Vector res=new Vector();
        try{
            fr=new FileReader(filename);
            bfr=new BufferedReader(fr);

            while((linea=bfr.readLine())!=null){
                 video=linea;
                 if((linea=bfr.readLine()).equals("\n"))
                     continue;
                 else{
                        res.add(video.concat(linea));
                 }
                 //System.out.println(video);
            }
        }
        catch(FileNotFoundException ex){
            ex.printStackTrace();
        }
        catch(IOException ex){
            ex.printStackTrace();
        }

        return res;
    }

     // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    /**
    * @param args : comandos de la línea de comandos.
    */
    public static void main(String args[]) {
        YouTubeService service;
        Youtube y=new Youtube("Dream Theater");
        service=new YouTubeService("Aplicación gdata");
        Vector v=new Vector();
        /*java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Youtube().setVisible(true);
            }
        });
        */
        v=y.searchFeed(service);
        y.genEmbed(v);
        Vector p=y.readEmbeds("Embeds.txt");
        System.out.println("CONTENIDO DE VIDEO:\n "+p.size());

        for(int i=0;i<p.size();i++)
            System.out.println(p.get(i)+"\n");
    }

    

}


